package com.card.user;

import org.jboss.netty.channel.ChannelHandlerContext;

import com.card.common.MessageComm;
import com.card.game.room.AbstractRoom;
import com.card.message.JsonMessageCenter;
import com.xiaoao.net.json.IMsgProcesser;
import com.xiaoao.net.json.Router;
import com.xiaoao.net.json.message.JsonMessage;

/**
 * 用户聊天相关管理类
 * 
 * @author Administrator
 *
 */
public class ChatLogic implements IMsgProcesser {
	private static final ChatLogic instance = new ChatLogic();

	public static ChatLogic getInstance() {
		return instance;
	}
	
	@Override
	public void registMsgId() {
		Router.getInstance().registMsg(MessageComm.C2S_Chat, this);
//		Router.getInstance().registMsg(1, this);
//		Router.getInstance().registMsg(2, this);
	}

	/**
	 * 消息逻辑处理
	 */
	@Override
	public void doProcess(int msgId, JsonMessage msg, ChannelHandlerContext ctx) {
		switch (msgId) {
			case MessageComm.C2S_Chat://聊天
				userChat(msg, ctx);
				break;
			case 1://聊天
				test1(msg, ctx);
				break;
			case 2://聊天
				test2(msg, ctx);
				break;
		}
	}

	/**
	 * 发送聊天信息
	 * @param msg
	 * @param ctx
	 */
	private void userChat(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();
		AbstractRoom room = user.getRoom();
		if(room == null) return;
		
		int type = msg.getAsInt("type");
		JsonMessage message = new JsonMessage(MessageComm.S2C_Chat);
		message.addProperty("userId", user.getPrimaryKey());
		message.addProperty("type", type);
		if(type == 0) {
			message.addProperty("data", msg.getAsString("data"));
		}else if(type == 1) {
			message.addProperty("data", msg.getAsString("data"));
		}
		room.broadcast(message);
	}
	
	private void test1(JsonMessage msg, ChannelHandlerContext ctx) {
//		System.err.println("==========");
		JsonMessage message = JsonMessage.createMessage(2);
		message.addProperty("1", "aasdd");
		message.addProperty("2", "aasdd");
		message.addProperty("3", "aasdd");
		message.addProperty("4", "aasdd");
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}
	private void test2(JsonMessage msg, ChannelHandlerContext ctx) {
//		System.err.println("客户端---收到消息---222");
	}
}
